<script setup lang="ts">
  import {
    useGetModuleList,
    useGetAddressList,
    useModulesDel,
  } from '@/services/pages/return-factory'
  import { ref } from 'vue'
  import { ElMessageBox, TableInstance } from 'element-plus'
  import infoTip from '@/config/info-tip'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import ModuleModal from './ModuleModal.vue'
  import { useRouter } from 'vue-router'

  const { del } = useModulesDel()
  const { addressList, getAddressListLoading, getAddressList } = useGetAddressList()
  const { total, moduleList, getModuleListParam, getModuleListLoading, getModulesList } =
    useGetModuleList()

  defineOptions({
    name: 'TableReturnFactorySetModule',
  })

  const emits = defineEmits<{
    (e: 'selection-change', value: Array<string>): void
  }>()

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 模块id选择集合
  const selectedModuleIds = ref<Array<string>>([])

  // 模块弹窗显示状态
  const moduleModalVisible = ref(false)

  // 正在编辑的模块id
  const editingModuleId = ref('')

  // 全局路由对象
  const router = useRouter()

  const findDefaultAddressById = (id: string) => {
    const address = addressList.value.find((address) => address.id === id)
    if (address) {
      return `${address.province} ${address.area} ${address.city} ${address.address}`
    }
    return ''
  }

  const handleChangeSelectedModuleIds = (moduleList: Array<ReturnFactoryModule>) => {
    selectedModuleIds.value = moduleList.map((module) => module.id)
    emits('selection-change', selectedModuleIds.value)
  }

  const handleDel = (module: ReturnFactoryModule) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(module, true)
      ElMessageBox({
        title: '提示',
        type: 'error',
        showCancelButton: true,
        message: infoTip.returnFactory.module.delOne,
        async beforeClose(action, instance, done) {
          if (['close', 'cancel'].includes(action)) {
            done()
            return
          }

          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            const res = await del(selectedModuleIds.value)
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (res.code === 20000) {
              HMessage.success(infoTip.returnFactory.module.multipleDelSuccess)
              done()
              getModulesList()
              getAddressList()
              return
            }

            HMessageBox.error(res.message)
          }
        },
      })
    }
  }

  const handleEdit = (id: string) => {
    editingModuleId.value = id
    moduleModalVisible.value = true
  }

  const handleToModuleDetail = (id: string) => {
    router.push({ path: `/return/factory/module/detail/${id}` })
  }

  defineExpose({
    total,
    getList: (param: typeof getModuleListParam.value) => {
      getModuleListParam.value = param
      getModulesList()
      getAddressList()
    },
  })
</script>

<template>
  <el-table
    ref="tableInstance"
    v-loading="getModuleListLoading || getAddressListLoading"
    height="100%"
    :border="true"
    :data="moduleList"
    scrollbar-always-on
    @selection-change="handleChangeSelectedModuleIds"
  >
    <el-table-column type="selection" width="50" :align="'center'" fixed="left"></el-table-column>
    <el-table-column
      type="index"
      width="50"
      :align="'center'"
      fixed="left"
      label="序号"
    ></el-table-column>
    <el-table-column label="模块名称" prop="name" show-overflow-tooltip min-width="140">
      <template #default="{ row }">
        <h-link @click="handleToModuleDetail(row.id)">{{ row.name }}</h-link>
      </template>
    </el-table-column>
    <el-table-column label="移动端显示" prop="mobileShow" width="100">
      <template #default="{ row }">
        {{ row.mobileShow ? '显示' : '隐藏' }}
      </template>
    </el-table-column>
    <el-table-column label="审核权限" width="100">
      <template #default="{ row }">
        {{ row.repairCheckRoot === 1 ? '自动审核' : '人工审核' }}
      </template>
    </el-table-column>
    <el-table-column label="审核方式" width="100">
      <template #default="{ row }">
        {{ row.repairCheckType === 1 ? '按整单审核' : '单独审核' }}
      </template>
    </el-table-column>
    <el-table-column label="条码校验" width="160">
      <template #default="{ row }">
        {{ row.enabledSnCodeCheck ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="选择网点" width="120">
      <template #default="{ row }">{{ row.enabledNetwork ? '允许选择' : '不允许选择' }}</template>
    </el-table-column>
    <el-table-column label="先发后收" width="140">
      <template #header>
        <div class="tip-table-cell-header">
          <span>先发后收</span>
          <el-tooltip effect="dark" content="允许后，可以不签收旧机也可以发新机" placement="top">
            <i class="iconfont icon-hangye-wulius"></i>
          </el-tooltip>
        </div>
      </template>
      <template #default="{ row }">
        {{ row.enabledFirstSendAfterIncom ? '允许' : '禁止' }}
      </template>
    </el-table-column>
    <el-table-column label="费用确认">
      <template #default="{ row }">
        {{ row.sureFee ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="检测流程" width="100">
      <template #default="{ row }">
        {{ row.enabledCheckProcess ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="服务报告">
      <template #default="{ row }">
        {{ row.enabledServiceReport ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="物流填写">
      <template #default="{ row }">
        {{ row.enableWriteLogistics ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="返厂签收">
      <template #default="{ row }">
        {{ row.enableRepairSignFor ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="默认返厂地址" width="200" show-overflow-tooltip>
      <template #default="{ row }">
        {{ findDefaultAddressById(row.repairAddrStoreId) }}
      </template>
    </el-table-column>
    <el-table-column label="故障库" width="100">
      <template #header>
        <div class="tip-table-cell-header">
          <span>故障库</span>
          <el-tooltip effect="dark" placement="top" content="新建返厂单时否开启故障库">
            <i class="iconfont icon-taizhanguzhang"></i>
          </el-tooltip>
        </div>
      </template>
      <template #default="{ row }">
        {{ row.enabledFault ? '开启' : '关闭' }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间" prop="createTime" width="140"></el-table-column>
    <el-table-column label="更新时间" prop="updateTime" width="140"></el-table-column>
    <el-table-column label="状态" fixed="right" :align="'center'">
      <template #default="{ row }">
        <div class="flex_justify_center">
          <h-status v-if="!row.status">启用</h-status>
          <h-status v-else type="info">禁用</h-status>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="100">
      <template #default="{ row }">
        <h-space>
          <h-link @click="handleEdit(row.id)">编辑</h-link>
          <h-link type="error" @click="handleDel(row)">删除</h-link>
        </h-space>
      </template>
    </el-table-column>

    <module-modal
      v-model:visible="moduleModalVisible"
      :module-id="editingModuleId"
      @update="getModulesList(), getAddressList()"
    ></module-modal>
  </el-table>
</template>

<style scoped lang="scss">
  .icon-hangye-wulius {
    color: $primaryColor;
  }

  .icon-taizhanguzhang {
    font-size: 14px;
    color: #007cff;
  }

  .tip-table-cell-header {
    display: flex;
    align-items: center;
    column-gap: 5px;

    .iconfont {
      font-size: 12px;
    }
  }
</style>
